﻿using NewRen.Helpers;
using NewRen.Models;
using NewRen.Schemas;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NewRen.Areas.Admin.Controllers
{
    [Schema.LoginCheck]
    public class UserGroupController : BaseController
    {

        #region 牛棚管理首页
        /// <summary>
        /// 牛棚管理首页
        /// </summary>
        /// <param name="key"></param>
        /// <param name="Begin"></param>
        /// <param name="End"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public ActionResult Index(string key, DateTime? Begin, DateTime? End, int p = 0)
        {
            IEnumerable<UserGroup> query = db.UserGroups.AsEnumerable();
            if (!string.IsNullOrEmpty(key))
            {
                query = query.Where(c => c.GroupName.Contains(key));
            }
            if (Begin.HasValue)
            {
                query = query.Where(c => c.AddTime >= Begin);
            }
            if (End.HasValue)
            {
                query = query.Where(c => c.AddTime <= End);
            }
            query = query.OrderByDescending(x => x.AddTime);
            ViewBag.PageInfo = PagerHelper.Do(ref query, 50, p);
            return View(query);
        }
        #endregion


        [HttpGet]
        public ActionResult Show(int id)
        {
            var group = new UserGroup();
            group = db.UserGroups.Find(id);
            ViewBag.Group = group;
            return View();
        }


        #region 图标显示
        /// <summary>
        /// 图标显示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ShowPicture(int id)
        {
            UserGroup group = new UserGroup();
            group = db.UserGroups.Find(id);
            return File(group.Picture, "image/jpg");
        }
        #endregion


        [HttpGet]
        public ActionResult Add()
        {
            var industries = db.Industries.ToList();
            var cities = db.Cities.ToList();
            ViewBag.Cities = cities;
            ViewBag.Industries = industries;
            return View();
        }


        #region 执行增加牛棚
        /// <summary>
        /// 执行增加牛棚  
        /// </summary>
        /// <param name="model"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Add(UserGroup model, HttpPostedFileBase file)
        {
            var industries = db.Industries.ToList();
            var cities = db.Cities.ToList();
            ViewBag.Industries = industries;
            ViewBag.Cities = cities;
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    System.IO.Stream stream = file.InputStream;
                    byte[] buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, (int)stream.Length);
                    stream.Close();
                    model.Picture = buffer;
                }
                model.LoginPassword = Helpers.Encryt.GetMD5(model.LoginPassword);
                model.AddTime = DateTime.Now;
                db.UserGroups.Add(model);
                db.SaveChanges();
                return Redirect("/Admin/UserGroup/Index");
            }
            else
            {
                ModelState.AddModelError("", "牛棚信息填写错误！");
            }
            return View();
        }
        #endregion

        #region 删除牛棚
        /// <summary>
        /// 删除牛棚
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        public ActionResult Delete(int id)
        {
            var group = new UserGroup();
            try
            {
                group = db.UserGroups.Find(id);
                db.UserGroups.Remove(group);
                db.SaveChanges();
                return Content("ok");
            }
            catch
            {
                return Content("fail");
            }

        }

        #endregion


        [HttpGet]
        public ActionResult Edit(int id)
        {
            var group = db.UserGroups.Find(id);
            ViewBag.Group = group;
            return View();
        }


        #region 修改牛棚
        /// <summary>
        /// 修改牛棚
        /// </summary>
        /// <param name="model"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(UserGroup model, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {

                var group = new UserGroup();
                group = db.UserGroups.Find(model.ID);
                if (file != null)
                {
                    System.IO.Stream stream = file.InputStream;
                    byte[] buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, (int)stream.Length);
                    stream.Close();
                    group.Picture = buffer;
                }
                group.GroupName = model.GroupName;
                group.Description = model.Description;
                group.City = model.City;
                group.Phone = model.Phone;
                group.LoginName = model.LoginName;
                group.LoginPassword = Helpers.Encryt.GetMD5(model.LoginPassword);
                group.Email = model.Email;
                group.WhatApp = model.WhatApp;
                group.Weibo = model.Weibo;
                group.Address = model.Address;
                group.Priority = model.Priority;
                db.SaveChanges();
                return Redirect("/Admin/UserGroup/Index");
            }
            else
            {
                ModelState.AddModelError("", "牛棚信息填写错误！");
            }
            return View();
        }

        #endregion

        #region 修改优先级
        /// <summary>
        /// 修改优先级
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult PriorityEdit(int id)
        {
            var group = db.UserGroups.Find(id);
            return View(group);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult PriorityEdit(int ID, int Priority)
        {
            var group = db.UserGroups.Find(ID);
            if (ModelState.IsValid)
            {
                try
                {
                    group.Priority = Priority;
                    db.SaveChanges();
                    return Redirect("/Admin/UserGroup/Index");
                }
                catch
                {
                    ModelState.AddModelError("", "修改失败，请重试！");
                }
            }
            else
            {
                ModelState.AddModelError("", "你输入的信息不正确，请重新输入！");
            }
            return View(group);
        }
        #endregion

        #region 牛棚认证
        /// <summary>
        /// 牛棚认证
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult VerifyEdit(int id)
        {
            var group = db.UserGroups.Find(id);
            return View(group);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult VerifyEdit(int ID, bool IsVerifed)
        {
            var group = db.UserGroups.Find(ID);
            try
            {
                group.IsVerified = IsVerifed;
                db.SaveChanges();
                return Redirect("/Admin/UserGroup/Index");
            }
            catch
            {
                ModelState.AddModelError("", "修改出错，请重试！");
                return View(group);
            }

        }
        #endregion

        public ActionResult Users(int id,int p=0)
        {
            var query = db.Users.AsEnumerable();
            query = query.Where(u => u.UserGroupID == id);
            query = query.OrderByDescending(x => x.AddTime);
            ViewBag.PageInfo = PagerHelper.Do(ref query, 16, p);
            return View(query);
        }


        /// <summary>
        /// 牛棚统计
        /// </summary>
        /// <returns></returns>
        public ActionResult Stat()
        {
            var now = DateTime.Now;
            var total = db.UserGroups.Count();
            var todayTotal = db.UserGroups.Where(g => g.AddTime.Year == now.Year && g.AddTime.Month == now.Month && g.AddTime.Day == now.Day).Count();
            ViewBag.Total = total;
            ViewBag.TodayTotal = todayTotal;
            return View();
        }

        /// <summary>
        /// 设置显示状态
        /// </summary>
        /// <returns></returns>
        public ActionResult SetShow(int id)
        {
            try
            {
                var group = db.UserGroups.Find(id);
                if (group.IsShow)
                {
                    group.IsShow = false;
                }
                else
                {
                    group.IsShow = true;
                }
                db.SaveChanges();
                return Redirect("/Admin/Business/Index");
            }
            catch
            {
                return Redirect("/Admin/Shared/Info?msg=修改牛人显示信息失败");
            }
        }
    }
}